package com.example.exp3.controller;


import com.example.exp3.service.ScheduleTask;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.text.html.HTMLDocument;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@RestController
public class api {

    @Autowired
    ScheduleTask scheduleTask;
    List<CSVRecord> recordList = null;
    ObjectMapper objectMapper = new ObjectMapper();

    @GetMapping("/getAllRecords")
    public List<Map<String, String>> getAllRecords() {
        recordList = scheduleTask.covid19csv.getAll();
        List<Map<String, String>> allRecord = new ArrayList<>();
        for (CSVRecord record : recordList) {
            Map<String, String> recordMap = record.toMap();
            allRecord.add(recordMap);
            System.out.println(recordMap);
        }
        return allRecord;
    }

    @GetMapping("/getRecord")
    public String getRecord(@RequestParam(value = "area", defaultValue = "Afghanistan") String area) throws JsonProcessingException {
        Map<String, String> result = null;
        recordList = scheduleTask.covid19csv.getAll();
        for (CSVRecord record : recordList) {
            if (record.get("Country/Region").equals(area) || record.get("Province/State").equals(area)) {
                result = record.toMap();
            }
        }
        System.out.println(area + " request");
        return objectMapper.writeValueAsString(result);
    }

}
